package ynu.edu.gateway.filter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import ynu.edu.common.constant.PermissionConstants;
import ynu.edu.common.exception.UnauthorizedException;
import ynu.edu.common.utils.CollUtils;
import ynu.edu.common.utils.RedisCache;
import ynu.edu.gateway.config.AuthProperties;
import ynu.edu.gateway.utils.JwtTool;
import java.util.List;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;
    private final AuthProperties authProperties;
    private final RedisCache redisCache;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        String method = request.getMethod().name();

        // 2.判断是否不需要拦截
        if(isExclude(path)){
            return chain.filter(exchange);
        }

        // 3.获取请求头中的token
        String token = getToken(request);
        if (token == null) {
            return unauthorized(exchange);
        }

        // 4.校验并解析token
        Long userId;
        try {
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            return unauthorized(exchange);
        }

        // 5.检查是否为不需要权限验证的路径
        if (isPublicPath(path)) {
            // 对于公开路径，只需要验证token有效即可，不需要检查权限
            ServerWebExchange swe = exchange.mutate()
                    .request(builder -> builder
                            .header("user-info", userId.toString())
                    )
                    .build();
            return chain.filter(swe);
        }

        // 6.从Redis获取权限并校验
        String cacheKey = PermissionConstants.PERMISSION_CACHE_PREFIX + userId;
        List<String> permissions = redisCache.getCacheObject(cacheKey);

        if (permissions == null || permissions.isEmpty()) {
            log.warn("用户[{}]未找到权限信息", userId);
            return forbidden(exchange);
        }

        // 6.简化权限校验
        boolean hasPermission = checkPermission(permissions, path);

        if (!hasPermission) {
            log.warn("用户[{}]没有访问[{}]的权限", userId, path);
            return forbidden(exchange);
        }

        // 7.放行请求
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder
                        .header("user-info", userId.toString())
                        .header("user-permissions", String.join(",", permissions))
                )
                .build();

        return chain.filter(swe);
    }

    private String getToken(ServerHttpRequest request) {
        List<String> headers = request.getHeaders().get("authorization");
        if (!CollUtils.isEmpty(headers)) {
            String token = headers.get(0);
            if (token.startsWith("Bearer ")) {
                return token.substring(7);
            }
            return token;
        }
        return null;
    }

    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }

    private Mono<Void> unauthorized(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    private Mono<Void> forbidden(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }


    // 新增方法：检查是否为公开路径（只需要token验证，不需要权限验证）
    private boolean isPublicPath(String path) {
        return path.startsWith("/home") || path.startsWith("/profile") || path.startsWith("/image")
                || path.contains("/login") || path.contains("/register") || path.contains("/logout")
                || path.startsWith("/products") || path.startsWith("/carts")
                || path.startsWith("/checkout") || path.startsWith("/orders")
                || path.startsWith("/addresses") || path.startsWith("/pay-orders");
    }

    private boolean checkPermission(List<String> permissions, String path) {
        // 这个方法现在只处理需要权限验证的路径
        // 对于公开路径，已经在 isPublicPath 中处理了
        String module = path.split("/")[1];
        return permissions.contains(module);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}